package cn.dataservice.executor.jobs;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;

import cn.hutool.core.io.FileUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@JobHandler(value = "AwsSqlJobHandler")
@Component
public class AwsSqlJobHandler extends IJobHandler {

	@Value("${aws.output}")
	private String outDir;

	@Value("${warn.output}")
	private String warnDir;

	private String awsSql = "select s.obtid,s.obtname,to_char(t.bj_datetime,'yyyymmddhh24miss') bj_datetime,"
			+ "	  t.t,t.u,t.p,w.wd10dd,w.wd10df,r.hourr,c.vvp10m"
			+ "  from cimiss.t_js_obt_min_temp t, cimiss.t_js_obt_min_cloud c, cimiss.t_js_obt_min_wind w, cimiss.t_js_obt_min_rain r,"
			+ "       nriet.T_JS_HDJ_STATION s where t.obtid = s.obtid and c.obtid = s.obtid and w.obtid = s.obtid"
			+ "   and r.obtid = s.obtid and t.bj_datetime = c.bj_datetime and t.bj_datetime = w.bj_datetime"
			+ "   and t.bj_datetime = r.bj_datetime and t.bj_datetime>=sysdate-10/1440 and t.bj_datetime<sysdate-5/1440";

	private String warnSql = "select * from T_JS_WARNING t where issuetime> sysdate-60/1440 order by issuetime desc";

	@Autowired
	private JdbcTemplate dao;

	@Override
	public ReturnT<String> execute(String param) throws Exception {

		XxlJobLogger.log("AwsSqlJobHandler INVOKED!");
		try {
			dealAwsJob();
			dealWarnJob();
		} catch (Exception e) {
			XxlJobLogger.log(e);
			return IJobHandler.FAIL;
		}
		return IJobHandler.SUCCESS;
	}

	void dealWarnJob() {
		List<Map<String, Object>> ret = dao.queryForList(warnSql);
		if (ret == null || ret.size() == 0) {
			XxlJobLogger.log("WarnSql NO RESULT RETURN!");
			return;
		}
		String fileName = String.valueOf(ret.get(0).get("ISSUETIME")).split("\\.")[0].replaceAll(":", "").replaceAll("-", "").replaceAll(" ", "") + ".txt";
		List<String> lines = new ArrayList<>();
		StringBuilder title = new StringBuilder();
		ret.forEach(m -> {
			StringBuilder sb = new StringBuilder();
			m.forEach((k, v) -> {
				sb.append(String.valueOf(v));
				sb.append(",");
			});
			sb.deleteCharAt(sb.length() - 1);
			lines.add(sb.toString());
		});
		ret.get(0).forEach((k, v) -> {
			title.append(k);
			title.append(",");
		});
		title.deleteCharAt(title.length() - 1);;
		File f = new File(warnDir, fileName);
		if (!f.exists()) {
			FileUtil.appendUtf8String(title + "\r\n", f);
			FileUtil.appendUtf8Lines(lines, f);
		}
	}

	void dealAwsJob() {
		List<Map<String, Object>> ret = dao.queryForList(awsSql);
		if (ret == null || ret.size() == 0) {
			XxlJobLogger.log("AwsSql NO RESULT RETURN!");
			return;
		}
		String fileName = String.valueOf(ret.get(0).get("BJ_DATETIME")).split("\\.")[0] + ".txt";
		List<String> lines = new ArrayList<>();

		ret.forEach(m -> {
			StringBuilder sb = new StringBuilder();
			m.forEach((k, v) -> {
				sb.append(String.valueOf(v));
				sb.append(",");
			});
			sb.deleteCharAt(sb.length() - 1);
			lines.add(sb.toString());
		});
		File f = new File(outDir, fileName);
		if (!f.exists()) {
			FileUtil.appendUtf8String("站号,站名,北京时间,温度,湿度,气压,十分钟平均风向,十分钟平均风速,过去一小时降水,十分钟平均能见度\r\n", f);
			FileUtil.appendUtf8Lines(lines, f);
		}

	}
}
